'use strict';

const Service = require('egg').Service;
const utils = require('../utils/utils');

class ProductService extends Service {
  async list({
    where = {},
    page_size = 10,
    page = 0,
  }) {
    if ('wareId' in where) {
      const childrenId = await this.classifyChildrenId(where.wareId);
      where.wareId = childrenId;
    }
    if ('keyword' in where) {
      const res = await this.app.mysql.query(`
        select * from product 
        where 
          title LIKE '%${where.keyword}%' 
        LIMIT 
          ${page * page_size}, ${page_size}
      `);
      return [ ...res ].map(item => {
        return {
          ...item,
          images: JSON.parse(item.images),
        };
      });
    }
    const res = await this.app.mysql.select('product', {
      where,
      limit: page_size * 1, // 条数
      offset: page * page_size, // 数据偏移量
    });
    return [ ...res ].map(item => {
      return {
        ...item,
        images: JSON.parse(item.images),
      };
    });
    
  }

  async classifyChildrenId(id) {
    const classify = await this.classify();
    const getChildrenId = (array, parentId, isParent = false) => {
      let ids = [];
      array.forEach(item => {
        if (isParent) {
          if (item.children) {
            ids = ids.concat(getChildrenId(item.children, parentId, true));
          } else {
            ids.push(item.id);
          }
        } else {
          if (item.id + '' === parentId) {
            ids = getChildrenId(item.children, parentId, true);
          } else if (item.children) {
            ids = ids.concat(getChildrenId(item.children, parentId));
          }
        }
      });
      return ids;
    };
    return getChildrenId(classify, id);
  }

  async classify() {
    const res = await this.app.mysql.select('classify');
    return utils.arrayToTree([ ...res ]);
  }

  async inster(data) {

    const pro = [];
    data.forEach(item => {
      pro.push(
        this.app.mysql.insert('product', {
          title: '第三批' + item.wareName,
          cover: item.wareImg,
          images: JSON.stringify([]),
          price: item.warePrice / 100,
          oldPrice: item.warePrice / 100,
          count: 100,
          volume: 10,
          brandId: 1,
        })
      );
    });
    const res = await Promise.all(pro);
    return res;
  }
}

module.exports = ProductService;
